package ynu.edu.elmservlet.controller;

import ynu.edu.elmservlet.po.Orders;
import ynu.edu.elmservlet.service.OrdersService;
import ynu.edu.elmservlet.service.impl.OrdersServiceImpl;
import ynu.edu.elmservlet.util.CommonUtil;
import jakarta.servlet.http.HttpServletRequest;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.ServletException;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.io.BufferedReader;

import jakarta.servlet.http.HttpServlet;

public class OrdersController extends HttpServlet {
    private final ObjectMapper objectMapper = new ObjectMapper();

    private Map<String, Object> getRequestData(HttpServletRequest request) throws Exception {
        String contentType = request.getContentType();
        
        final Map<String, Object> data = new HashMap<>();
        if (contentType != null && contentType.contains("application/x-www-form-urlencoded")) {
            request.getParameterMap().forEach((key, value) -> {
                if (value != null && value.length > 0) {
                    data.put(key, value[0]);
                }
            });
        } else {
            BufferedReader reader = request.getReader();
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            Map<String, Object> jsonData = objectMapper.readValue(sb.toString(), Map.class);
            data.putAll(jsonData);
        }
        
        System.out.println("Parsed request data: " + data);
        return data;
    }

    public Object createOrders(HttpServletRequest request) throws Exception {
        try {
            Map<String, Object> data = getRequestData(request);
            System.out.println("Create orders data: " + data);
            
            // 获取用户ID
            String userId = (String) request.getAttribute("userId");
            if (userId == null || userId.trim().isEmpty()) {
                System.out.println("User ID is missing");
                return 0;
            }
            
            // 创建订单对象
            Orders orders = new Orders();
            orders.setUserId(userId);
            orders.setBusinessId(Integer.valueOf(data.get("businessId").toString()));
            orders.setDaId(Integer.valueOf(data.get("daId").toString()));
            orders.setOrderTotal(Double.valueOf(data.get("orderTotal").toString()));
            orders.setOrderDate(CommonUtil.getCurrentDate());
            orders.setOrderState(0);  // 0表示未支付
            
            OrdersService service = new OrdersServiceImpl();
            int orderId = service.saveOrders(orders);  // 使用 saveOrders 而不是 createOrders
            
            System.out.println("Created order ID: " + orderId);
            return orderId;
        } catch (Exception e) {
            System.out.println("Create orders error: " + e.getMessage());
            e.printStackTrace();
            return 0;
        }
    }

    public Object getOrdersById(HttpServletRequest request) throws Exception {
        try {
            Integer orderId = Integer.valueOf(request.getParameter("orderId"));
            
            OrdersService service = new OrdersServiceImpl();
            Orders orders = service.getOrdersById(orderId);
            
            if (orders == null) {
                System.out.println("Order not found: " + orderId);
                return null;
            }
            
            // 打印订单信息用于调试
            System.out.println("Order found: " + orderId);
            System.out.println("Business info: " + orders.getBusiness());
            System.out.println("Order details: " + orders.getOrderDetailetList());
            
            return orders;
        } catch (Exception e) {
            System.out.println("Get order error: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    public Object listOrdersByUserId(HttpServletRequest request) throws Exception {
        String userId = request.getParameter("userId");
        OrdersService service = new OrdersServiceImpl();
        List<Orders> list = service.listOrdersByUserId(userId);
        return list;
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String op = request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/") + 1);
        
        try {
            if ("getOrdersById".equals(op)) {
                writeValue(getOrdersById(request), response);
            } else if ("listOrdersByUserId".equals(op)) {
                writeValue(listOrdersByUserId(request), response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String op = request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/") + 1);
        
        try {
            if ("createOrders".equals(op)) {
                writeValue(createOrders(request), response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    private void writeValue(Object obj, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        objectMapper.writeValue(response.getOutputStream(), obj);
    }
}